package com.hns.tool.pub;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Iterator;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

public class UtilString {

	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	private static final ObjectMapper objMap = new ObjectMapper();

	/**
	 * 将对象转换为JSON字符串
	 * 
	 * @return
	 * @author yulj
	 * @Date 2013-5-15
	 */
	public static String object2Json(Object val) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			objMap.writeValue(bos, val);
			String res = bos.toString("UTF-8");
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				bos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 解析json字符串 为 java对象
	 * 
	 * @param json
	 * @param clazz
	 * @return
	 * @throws Exception
	 */
	public static <T> T json2Object(String json, Class<T> clazz) throws Exception {
		return objMap.readValue(json, clazz);
	}

	public static String getMD5(String original) {
		String s = null;
		if (original == null) {
			return s;
		}
		byte[] source = original.getBytes();
		char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
			// 用字节表示就是 16 个字节
			char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
			// 所以表示成 16 进制需要 32 个字符
			int k = 0; // 表示转换结果中对应的字符位置
			for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
				// 转换成 16 进制字符的转换
				byte byte0 = tmp[i]; // 取第 i 个字节
				str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
				// >>> 为逻辑右移，将符号位一起右移
				str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
			}
			s = new String(str); // 换后的结果转换为字符串

		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}

	public static boolean isEmpty(String str) {
		return str == null || str.trim().length() == 0;
	}

	public static boolean isNotEmpty(String str) {
		return str != null && str.trim().length() > 0;
	}

	public static String list2String(Collection<String> list) {
		return list2String(list, ",");
	}

	public static String list2String(Collection<String> list, String split) {
		if (list == null || list.size() == 0) {
			return "";
		}
		Iterator<String> it = list.iterator();
		StringBuilder sb = new StringBuilder();
		sb.append(it.next());
		while (it.hasNext()) {
			sb.append(split);
			sb.append(it.next());
		}
		return sb.toString();
	}

	/**
	 * 字符串转Unicode
	 * 
	 * @param s
	 * @return
	 */
	public static String string2Unicode(String s) {
		try {
			StringBuffer out = new StringBuffer("");
			byte[] bytes = s.getBytes("unicode");
			for (int i = 2; i < bytes.length - 1; i += 2) {
				out.append("u");
				String str = Integer.toHexString(bytes[i + 1] & 0xff);
				for (int j = str.length(); j < 2; j++) {
					out.append("0");
				}
				String str1 = Integer.toHexString(bytes[i] & 0xff);

				out.append(str);
				out.append(str1);

			}
			return out.toString().toUpperCase();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static int string2Int(String s, int defaultValue) {
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	public static long string2Long(String s, long defaultValue) {
		try {
			return Long.parseLong(s);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	static final String regEx = "['/']+";

	public static String toLinuxPath(String s) {
		s = s.replace("\\", "/");
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(s);
		return m.replaceAll("/");
	}

	public static String toRelativePath(String s) {
		s = toLinuxPath(s);
		if (!s.endsWith("/")) {
			s += "/";
		}
		return s;
	}

	/**
	 * 将字符串数组的元素以指定连接符unionChar拼接成字符串，每个数组元素前后都将添加appendChar。
	 * 
	 * <p>
	 * <strong>用例描述：</strong>
	 * 
	 * <pre>
	 * getUnionStr(new String[] { &quot;A&quot;, &quot;B&quot;, &quot;C&quot; }, &quot;,&quot;, &quot;&quot;) = &quot;A,B,C&quot;;
	 * getUnionStr(new String[] { &quot;A&quot;, &quot;B&quot;, &quot;C&quot; }, &quot;,&quot;, &quot;*&quot;) = &quot;*A*,*B*,*C*&quot;;
	 * </pre>
	 * 
	 * @params strAry 用于连接的字符串数组
	 * @params unionChar 用来连接的中间字符
	 * @params appendChar 用来在每个字符中追加
	 */
	public static String getUnionStr(String[] strAry, String unionChar, String appendChar) {
		StringBuffer ret = new StringBuffer();
		for (int i = 0; i < strAry.length; i++) {
			if (i != 0)
				ret.append(unionChar);
			ret.append(appendChar + strAry[i] + appendChar);
		}
		return ret.toString();
	}

	/**
	 * 获取汉字首字母
	 * 
	 * @param str
	 * @return
	 * @author yulj
	 * @Date 2013-5-27
	 */
	public static String getHeadChar(String str) {
		String convert = "";
		for (int j = 0; j < str.length(); j++) {
			char word = str.charAt(j);
			// 提取汉字的首字母
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) {
				convert += pinyinArray[0].charAt(0);
			} else {
				convert += word;
			}
		}
		return convert;
	}

	/**
	 * 汉字转拼音
	 * 
	 * @param src
	 * @return
	 * @author yulj
	 * @Date 2013-5-27
	 */
	public static String getPinYin(String src) {
		char[] t1 = null;
		t1 = src.toCharArray();
		String[] t2 = new String[t1.length];
		// 设置汉字拼音输出的格式
		HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
		t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		t3.setVCharType(HanyuPinyinVCharType.WITH_V);
		String t4 = "";
		int t0 = t1.length;
		try {
			for (int i = 0; i < t0; i++) {
				// 判断是否为汉字字符
				// System.out.println(t1[i]);
				if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
					t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);// 将汉字的几种全拼都存到t2数组中
					t4 += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4后
				} else {
					// 如果不是汉字字符，直接取出字符并连接到字符串t4后
					t4 += Character.toString(t1[i]);
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return t4;
	}

	/**
	 * 十六进制转汉字(用于解释前台十六进制参数)
	 * 
	 * @param str
	 * @return
	 * @author yulj
	 * @Date 2013-6-6
	 */
	public static String getChinese(String str) {
		str = str.replace('\\', '/');
		StringBuffer sb = new StringBuffer();
		String[] items = str.split("/x");
		for (String item : items) {
			if (!isNotEmpty(item)) {
				continue;
			}
			int c = Integer.parseInt(item, 16);
			sb.append((char) c);
		}
		return sb.toString();
	}

	/**
	 * 字符串转16进制
	 * @param s
	 * @return
	 */
	public static String toHexString(String s) { 
		String str=""; 
		for (int i=0;i<s.length();i++) { 
			int ch = (int)s.charAt(i); 
			String s4 = Integer.toHexString(ch); 
			str += "\\x" + s4; 
		} 
		return str; 
	} 
	
	public static String filterNULLSPACE(Object target) {
        if (isNotEmpty(target)) {
            return StringUtils.trimWhitespace(target.toString());
        } else {
            return "";
        }
    }

    /**
     * @param target
     * @return
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     * @创建日期:2014-3-28
     * @功能说明：过滤所有空格
     */
    public static String filterNULLAllSPACE(Object target) {
        if (isNotEmpty(target)) {
            return StringUtils.trimAllWhitespace(target.toString());
        } else {
            return "";
        }
    }
    
    /**
     * @param target
     * @return
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     * @创建日期:2014-3-28
     * @功能说明：判断字符串是否为数字
     */
    public static boolean isNumber(String target) {
        if(null != target && !"".equals(target) && !"null".equals(target)){
            return target.matches("[0-9]*");
        }else{
            return false;
        }
    }
    
    public static boolean isNotEmpty(Object target) {
        return null != target && !"".equals(target) && !"null".equals(target);
    }

    public static void main(String[] args){
    	System.out.println(getUUID());
	}

}
